import { DistributionWay } from '../constants';

const DistributionWayStatus = {
  // 存在交集
  intersection: true,
  // 存在空集
  emptySet: false,
};

function groupByDistributionWay(productList) {
  let result = Object.values(DistributionWay).reduce(
    (r, v) => {
      r[v] = [];
      return r;
    },
    { emptySet: [] },
  );

  productList?.forEach((product) => {
    const { distributionWayList } = product;

    // 没有配送方式
    if (!distributionWayList?.length) {
      result.emptySet.push(product);
      return;
    }

    Object.keys(DistributionWay).forEach((key) => {
      const way = DistributionWay[key];

      if (distributionWayList.includes(way)) {
        result[way].push(product);
      }
    });
  });

  return result;
}

function checkDistributionWay(productList) {
  let group = groupByDistributionWay(productList);

  if (group.emptySet?.length) {
    return DistributionWayStatus.emptySet;
  }

  const isAllMatch = Object.values(group).find((arr) => {
    if (arr.length === productList.length) {
      return true;
    }
  });

  if (isAllMatch) {
    return DistributionWayStatus.intersection;
  }

  return group;
}

export { checkDistributionWay, DistributionWayStatus };
